import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zhibao_flutter/api/commom/common_entity.dart';
import 'package:zhibao_flutter/zone.dart';

// AreaCodeSearchDelegate
class AreaCodeSearchDelegate extends SearchDelegate<AreaCode?> {
  final List<AreaCode> countryCodes;

  AreaCodeSearchDelegate(this.countryCodes);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    final results = countryCodes.where((countryCode) {
      final name = AppConfig.locale.languageCode == "en"
          ? countryCode.englishName
          : countryCode.chineseName;
      return name.toLowerCase().contains(query.toLowerCase());
    }).toList();

    return ListView.builder(
      itemCount: results.length,
      itemBuilder: (context, index) {
        final item = results[index];
        final name = AppConfig.locale.languageCode == "en"
            ? item.englishName
            : item.chineseName;
        return ListTile(
          title: Text(name),
          onTap: () {
            close(context, results[index]);
          },
        );
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return buildResults(context);
  }
}

typedef OnAreaCodeSelected = void Function(AreaCode? countryCode);

void showAreaCodeDialog(
    BuildContext context, OnAreaCodeSelected onAreaCodeSelected) {
  showDialog(
    context: context,
    builder: (context) {
      return ShowAreaCodeDialog(onAreaCodeSelected);
    },
  );
}

class ShowAreaCodeDialog extends StatefulWidget {
  final OnAreaCodeSelected onAreaCodeSelected;

  ShowAreaCodeDialog(this.onAreaCodeSelected);

  @override
  State<ShowAreaCodeDialog> createState() => _ShowAreaCodeDialogState();
}

class _ShowAreaCodeDialogState extends State<ShowAreaCodeDialog>
    with AutomaticKeepAliveClientMixin {
  List<AreaCode> countryCodes = <AreaCode>[
    // AreaCode('China', '+86'),
    // AreaCode('United States', '+1'),
    // Add all country codes here
  ];

  @override
  void initState() {
    super.initState();
    getData();
  }

  Future getData() async {
    /// Get content from asset file `assets/data/countryCodeAndPhoneCode.json`.
    String jsonString =
        await rootBundle.loadString('assets/data/countryCodeAndPhoneCode.json');
    json.decode(jsonString).forEach((v) {
      countryCodes.add(AreaCode.fromJson(v));
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return AlertDialog(
      title: Text("selectAreaCode".tr),
      actions: [
        IconButton(
          icon: Icon(Icons.search),
          onPressed: () async {
            final selectedAreaCode = await showSearch(
              context: context,
              delegate: AreaCodeSearchDelegate(countryCodes),
            );

            if (selectedAreaCode != null) {
              widget.onAreaCodeSelected(selectedAreaCode);
              Navigator.of(context).pop();
            }
          },
        ),
      ],
      content: SizedBox(
        height: Get.height,
        width: Get.width,
        child: ListView.builder(
          itemCount: countryCodes.length,
          itemBuilder: (context, index) {
            final item = countryCodes[index];
            final name = AppConfig.locale.languageCode == "en"
                ? item.englishName
                : item.chineseName;
            return ListTile(
              title: Text('$name (${countryCodes[index].phoneCode})'),
              onTap: () {
                widget.onAreaCodeSelected(countryCodes[index]);
                Navigator.of(context).pop();
              },
            );
          },
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
